<?php

namespace App\Http\Controllers\Admin;

use App\Models\Site;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class SiteController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = [
            'base' => [],
            'app' => []
        ];
        $config = Site::select(['value', 'key', 'type'])
            ->whereIn('type', ['base', 'app'])
            ->get()
            ->toArray();
        if (!empty($config)) {
            foreach ($config as $item) {
                $data[$item['type']][$item['key']] = $item['value'];
            }
        }

        return view('admin.site.app', $data);
    }

    /**
     * Show the form for creating a new resource.
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 更新/新建配置
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $type = $request->get('_type', 'base');
        $data = $request->except(['_token', '_method', '_type']);
        if (empty($data)) {
            return back()->withErrors(['status' => '无数据更新']);
        }
        foreach ($data as $key => $val) {
            Site::updateOrCreate(['key' => $key, 'type' => $type], ['value' => $val]);
        }
        return back()->with(['status' => '更新成功']);
    }

    /**
     * Remove the specified resource from storage.
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
